package sale

import (
    "time"
	"strconv"
	"dhfshop/models/sale"
	"dhfshop/controllers/base"
	//"dhfshop/service"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

// 卖家商品分类管理
type CatController struct {
	base.BaseController
}

func (this *CatController) PubItemCatsList() {
    query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	if len(query) == 0 {
	   query["parent_cid"] = "0"
	}
	var allowStoreId []int64
	if this.CurrentUser != nil {
	    allowStoreId = this.CurrentUser.AllowStoreId
	}
	//beego.Debug("allowStoreId:", allowStoreId)
	order_by["sort"] = "asc"
	l, num, err := sale.GetAllItemCats(allowStoreId,query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	   
	} 
	r := struct {
	       TotalCount  int64              `json:"total_count"`
	       ItemCats    []*sale.ItemCat  `json:"itemcats"`
	    }{TotalCount: num, ItemCats: l}
	this.Data["json"] = r
	this.ServeJSON()
}


// 获取卖家自定义商品类目
func (this *CatController) ItemCatsList() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
    partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
    query["partner_id"] = strconv.FormatInt(partnerId, 10)
    var allowStoreId []int64
	if this.CurrentUser != nil {
	    allowStoreId = this.CurrentUser.AllowStoreId
	}
	//beego.Debug("allowStoreId:", allowStoreId)
	order_by["sort"] = "asc"
	l, num, err := sale.GetAllItemCats(allowStoreId,query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	   
	} 
	r := struct {
	       TotalCount  int64              `json:"total_count"`
	       ItemCats    []*sale.ItemCat  `json:"itemcats"`
	    }{TotalCount: num, ItemCats: l}
	this.Data["json"] = r
	this.ServeJSON()
}


func (this *CatController) Post() {
	var v sale.ItemCat
	this.ParseForm(&v)
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	valid := validation.Validation{}
	valid.Required(v.PartnerId, "partner_id")
	valid.Required(v.ParentCid, "parent_cid")
	valid.Required(v.Name, "name")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	} 
	parent_cats, err := sale.GetItemCatById(v.ParentCid)
	if err != nil {
	    this.ServeError(err.Error())
		return
	}
	v.Lft = parent_cats.Lft + 1
    v.Rgt = parent_cats.Lft + 2
    v.Level = parent_cats.Level + 1
	cid, err := sale.BatchAddCid(&v,parent_cats.Lft)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	v.Cid = cid
	rsp := struct {
		Cid       int64        `json:"cid"`
	    Created   time.Time    `json:"created"`
	}{Cid: v.Cid, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

func (this *CatController) Put() {
    //companyId := this.Ctx.Input.GetData("curCompanyId").(int)
    //curUserId := this.Ctx.Input.GetData("curUserId").(int)
	v := struct {
		Cid          int64   `form:"cid" valid:"Required"`
	    Name         string  `form:"name"`
		Sort         int     `form:"sort"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
	    this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	//beego.Debug("cid:", v.Cid, "name:", v.Name, "sort:", v.Sort)
	itemcat, err := sale.GetItemCatById(v.Cid); 
	if err != nil {
		this.ServeError(err.Error())
		return 
	}
	updateFields := []string{}
	if v.Name != itemcat.Name {
	    itemcat.Name = v.Name
		updateFields = append(updateFields, "name")
	}
	if v.Sort != itemcat.Sort {
	    itemcat.Sort = v.Sort
		updateFields = append(updateFields, "sort")
	}
	if err := sale.UpdateItemCatById(itemcat, updateFields...); err != nil {
	    this.ServeError(err.Error())
		return 
    }
	rsp := struct {
		    Cid       int64       `json:"cid"`
	        Modified  time.Time   `json:"modified"`
	}{Cid:v.Cid, Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}	

// 
func (this *CatController) Delete() {
	//companyId := this.Ctx.Input.GetData("curCompanyId").(int)
    //curUserId := this.Ctx.Input.GetData("curUserId").(int)
	cidStr := this.GetString("cid")
	if cidStr == "" {
	    this.ServeError("cid is null")
	    return
	}
	cid, _ := strconv.ParseInt(cidStr, 10, 0)
	if err := sale.DeleteItemCat(cid); err != nil {
	    this.ServeError(err.Error())
	    return
	}
    r := struct {
		    Cid       int64       `json:"cid"`
	        Modified  time.Time   `json:"modified"`
	    }{Cid:cid, Modified:time.Now().UTC()}
	this.Data["json"] = r 
	this.ServeJSON()
}



